<template>
  <div class="personal-center-container">
    <!-- 头部 -->
    <MainHeader/>

    <!-- 主要内容区 -->
    <div class="main-container">
      <!-- 侧边菜单 -->
      <SideMenu/>

      <!-- 右侧内容区 -->
      <div class="content">
        <!-- 水平标签页菜单 -->
        <div class="horizontal-menu">
          <div
              v-for="(tab, index) in tabs"
              :key="index"
              :class="['menu-item', { active: activeTab === tab.name }]"
              @click="activeTab = tab.name"
          >
            {{ t(tab.translationKey) }}
          </div>
        </div>

        <!-- 标签页内容区域 -->
        <div class="tab-content">
          <!-- 我的账户标签页 -->
          <div v-if="activeTab === 'myAccount'" class="tab-section">
            <div v-if="!isLoggedIn" class="login-prompt">
              <el-icon :size="64" class="prompt-icon">
                <Lock/>
              </el-icon>
              <p class="prompt-title">{{ t('personalCenter.needLogin') }}</p>
              <p class="prompt-desc">{{ t('personalCenter.pleaseLoginFirst') }}</p>
              <el-button type="primary" @click="goToLogin">{{ t('personalCenter.goToLogin') }}</el-button>
            </div>

            <template v-else>
              <div class="transaction-history">
                <!-- 用户信息概览 -->
                <div class="user-stats-overview">
                  <div class="stats-header">
                    <h3>{{ t('personalCenter.userBalanceInfo') }}</h3>
                    <el-button type="primary" size="small" @click="fetchUserBalance" :loading="balanceLoading">
                      <el-icon>
                        <Refresh/>
                      </el-icon>
                      {{ t('personalCenter.refresh') }}
                    </el-button>
                  </div>

                  <div class="form-group-row">
                    <div class="form-label">{{ t('personalCenter.memberLevel') }}：</div>
                    <div class="form-value">
                      <span class="member-badge"
                            :class="`level-${userBalances.memberLevel}`">{{ userBalances.memberLevelText }}</span>
                    </div>
                  </div>

                  <div class="form-group-row">
                    <div class="form-label">{{ t('personalCenter.remainingExportRecords') }}：</div>
                    <div class="form-value">{{ userBalances.exportQuotaRemaining }}</div>
                  </div>

                  <div class="form-group-row">
                    <div class="form-label">{{ t('personalCenter.remainingViewRecords') }}：</div>
                    <div class="form-value">{{ userBalances.viewPagesRemaining }}</div>
                  </div>

                  <div class="form-group-row">
                    <div class="form-label">{{ t('personalCenter.remainingLookupRecords') }}：</div>
                    <div class="form-value">{{ userBalances.reverseLookupRemaining }}</div>
                  </div>

                  <div class="form-group-row">
                    <div class="form-label">{{ t('personalCenter.remainingEmailSend') }}：</div>
                    <div class="form-value">{{ userBalances.emailSendRemaining }}</div>
                  </div>

                  <div class="form-group-row">
                    <div class="form-label">{{ t('personalCenter.emailPackageLevel') }}：</div>
                    <div class="form-value">
                      <span>{{
                          userBalances.emailPackageName || getEmailPackageLevelText(userBalances.emailPackageLevel)
                        }}</span>
                    </div>
                  </div>

                  <div class="form-group-row">
                    <div class="form-label">{{ t('personalCenter.vipExpireDate') }}：</div>
                    <div class="form-value">{{ formatDate(userBalances.vipExpireDate) }}</div>
                  </div>
                  <div class="form-group-row">
                    <div class="form-label">{{ t('personalCenter.updateTime') }}：</div>
                    <div class="form-value">{{ formatDate(userBalances.updatedAt) }}</div>
                  </div>
                </div>

                <!-- 在标题部分显示充值记录而非交易明细 -->
                <div class="section-title fancy-title">{{ t('personalCenter.rechargeRecords') }}</div>

                <div class="history-filter">
                  <div class="filter-btns" style="margin-left: 20px;">
                    <el-radio-group v-model="transactionType" @change="fetchTransactions">
                      <el-radio-button value="">{{ t('personalCenter.all') }}</el-radio-button>
                      <el-radio-button value="CUSTOM">{{ t('personalCenter.customRecharge') }}</el-radio-button>
                      <el-radio-button value="VIP">{{ t('personalCenter.vipPackage') }}</el-radio-button>
                      <el-radio-button value="EMAIL">{{ t('personalCenter.emailPackage') }}</el-radio-button>
                    </el-radio-group>
                  </div>
                </div>

                <div class="table-container">
                  <div class="table-header-actions">
                    <span class="record-count">{{
                        t('personalCenter.totalRecords', {count: transactions.length})
                      }}</span>
                    <el-button
                        type="primary"
                        size="small"
                        @click="fetchTransactions"
                        :loading="transactionsLoading"
                        icon="Refresh"
                    >
                      {{ t('personalCenter.refresh') }}
                    </el-button>
                  </div>

                  <el-table
                      v-loading="transactionsLoading"
                      :data="paginatedTransactions"
                      style="width: 100%"
                      border
                  >
                    <el-table-column
                        prop="id"
                        :label="t('personalCenter.id')"
                        width="80"
                    />
                    <el-table-column
                        prop="phone"
                        :label="t('personalCenter.phone')"
                        width="120"
                    />
                    <el-table-column
                        prop="rechargeType"
                        :label="t('personalCenter.type')"
                        width="100"
                    >
                      <template #default="scope">
                        <el-tag :type="getRechargeTypeTagType(scope.row.rechargeType)">
                          {{ getRechargeTypeText(scope.row.rechargeType) }}
                        </el-tag>
                      </template>
                    </el-table-column>
                    <el-table-column
                        prop="packageId"
                        :label="t('personalCenter.packageId')"
                        width="80"
                    />
                    <el-table-column
                        prop="amount"
                        :label="t('personalCenter.amount')"
                        width="120"
                    >
                      <template #default="scope">
                        <span :style="{ color: Number(scope.row.amount) >= 0 ? '#67c23a' : '#f56c6c' }">
                          {{ formatAmount(scope.row.amount) }}
                        </span>
                      </template>
                    </el-table-column>
                    <el-table-column
                        prop="quotaAdded"
                        :label="t('personalCenter.quotaAdded')"
                        width="100"
                    />
                    <el-table-column
                        prop="description"
                        :label="t('personalCenter.description')"
                        min-width="150"
                    />
                    <el-table-column
                        prop="orderNo"
                        :label="t('personalCenter.orderNo')"
                        width="120"
                    />
                    <el-table-column
                        prop="paymentMethod"
                        :label="t('personalCenter.paymentMethod')"
                        width="100"
                    >
                      <template #default="scope">
                        <el-tag :type="getPaymentMethodTagType(scope.row.paymentMethod)">
                          {{ getPaymentMethodText(scope.row.paymentMethod) }}
                        </el-tag>
                      </template>
                    </el-table-column>
                    <el-table-column
                        prop="status"
                        :label="t('personalCenter.status')"
                        width="80"
                    >
                      <template #default="scope">
                        <el-tag :type="getStatusTagType(scope.row.status)">
                          {{ getStatusText(scope.row.status) }}
                        </el-tag>
                      </template>
                    </el-table-column>
                    <el-table-column
                        prop="createdAt"
                        :label="t('personalCenter.creationTime')"
                        width="160"
                    >
                      <template #default="scope">
                        {{ formatDate(scope.row.createdAt) }}
                      </template>
                    </el-table-column>
                  </el-table>

                  <div class="pagination-container" v-if="transactions.length > 0">
                    <el-pagination
                        background
                        layout="prev, pager, next, sizes, total"
                        :total="transactions.length"
                        :page-size="pageSize"
                        :current-page="currentPage"
                        :page-sizes="[10, 20, 50, 100]"
                        @current-change="handleCurrentChange"
                        @size-change="handleSizeChange"
                    />
                  </div>

                  <div v-if="transactions.length === 0 && !transactionsLoading" class="empty-data-container">
                    <div class="empty-data">
                      <el-icon :size="64" class="empty-icon">
                        <Document/>
                      </el-icon>
                      <p>{{ t('personalCenter.noRechargeRecords') }}</p>
                      <p class="empty-hint">{{ t('personalCenter.rechargeShowHere') }}</p>
                    </div>
                  </div>
                </div>
              </div>

              <!-- 充值对话框 -->
              <el-dialog
                  :title="t('personalCenter.accountRecharge')"
                  v-model="showRechargeDialog"
                  width="400px"
                  @closed="resetRechargeForm"
              >
                <el-form ref="rechargeFormRef" :model="rechargeForm" :rules="rechargeRules" label-width="80px">
                  <el-form-item :label="t('personalCenter.rechargeAmount')" prop="amount">
                    <el-input-number v-model="rechargeForm.amount" :min="1" :precision="2" style="width: 100%"/>
                  </el-form-item>
                </el-form>
                <template #footer>
                  <div class="dialog-footer">
                    <el-button @click="showRechargeDialog = false">{{ t('common.cancel') }}</el-button>
                    <el-button type="primary" @click="handleRecharge" :loading="rechargeLoading">
                      {{ t('personalCenter.rechargeNow') }}
                    </el-button>
                  </div>
                </template>
              </el-dialog>
            </template>
          </div>

          <!-- 会员中心标签页 -->
          <div v-if="activeTab === 'memberCenter'" class="tab-section membership-section">
            <div class="section-title fancy-title">{{ t('personalCenter.memberVersion') }}</div>

            <!-- 会员套餐说明 -->
            <div class="vip-description">
              <div class="description-title">{{ t('personalCenter.memberPrivilegeDesc') }}</div>
              <ul class="description-list">
                <li>
                  <el-icon color="#67c23a">
                    <Check/>
                  </el-icon>
                  {{ t('personalCenter.privilegeAutoAdd') }}
                </li>
                <li>
                  <el-icon color="#67c23a">
                    <Check/>
                  </el-icon>
                  {{ t('personalCenter.validityPeriod') }}
                </li>
                <li>
                  <el-icon color="#67c23a">
                    <Check/>
                  </el-icon>
                  {{ t('personalCenter.upgradeBenefits') }}
                </li>
                <li>
                  <el-icon color="#67c23a">
                    <Check/>
                  </el-icon>
                  {{ t('personalCenter.quotaContinuedUse') }}
                </li>
              </ul>
            </div>

            <!-- 当前会员信息 -->
            <div class="current-vip-info" v-if="isLoggedIn && userInfo.memberLevel > 0">
              <div class="vip-badge" :class="`level-${userInfo.memberLevel}`">
                {{ getMemberLevelText(userInfo.memberLevel) }}
              </div>
              <div class="vip-expire" v-if="vipExpireDate">
                {{ t('personalCenter.validUntil') }}: {{ formatDate(vipExpireDate) }}
                <span class="expire-countdown" :class="{ 'warning': vipDaysLeft && vipDaysLeft < 30 }">
                  ({{ t('personalCenter.remainingDays', {days: vipDaysLeft}) }})
                </span>
              </div>
            </div>

            <div v-loading="vipLoading" class="membership-plans">
              <!-- 动态渲染VIP套餐 -->
              <div v-for="pkg in vipPackages" :key="pkg.id"
                   class="plan-card"
                   :class="{
                  'free-plan': pkg.level === 0,
                  'current-plan': userInfo.memberLevel === pkg.level,
                  [`level-${pkg.level}-plan`]: true
                }"
                   :style="getPlanCardStyle(pkg.level)">
                <div class="plan-tag"
                     :class="`level-${pkg.level}-tag`"
                     :style="getPlanTagStyle(pkg.level)">{{ pkg.name }}
                </div>
                <div class="plan-desc">{{ pkg.description }}</div>
                <div class="plan-price">¥ {{ pkg.price }}</div>
                <div class="plan-duration" v-if="pkg.duration > 0">{{ pkg.duration }} {{
                    t('personalCenter.months')
                  }}
                </div>

                <div v-if="userInfo.memberLevel === pkg.level" class="current-plan-badge">
                  <span>{{ t('personalCenter.currentPlan') }}</span>
                </div>

                <el-button class="plan-btn upgrade-btn"
                           @click="handleUpgrade(pkg.level)"
                           :loading="vipPurchaseLoading"
                           :style="getPlanButtonStyle(pkg.level)">
                  {{ userInfo.memberLevel > pkg.level ? t('personalCenter.downgrade') : t('personalCenter.upgrade') }}
                </el-button>

                <div class="plan-features">
                  <div class="feature-title">{{ t('personalCenter.includedFeatures') }}</div>
                  <div class="feature-list">
                    <div class="feature-item" :class="{ 'disabled': pkg.level === 0 }">
                      <el-icon :color="pkg.level === 0 ? '#f56c6c' : '#67c23a'">
                        <component :is="pkg.level === 0 ? 'Close' : 'Check'"/>
                      </el-icon>
                      <span>{{ pkg.level === 0 ? t('personalCenter.basicQuery') : t('personalCenter.allData') }}</span>
                    </div>
                    <div class="feature-item">
                      <el-icon color="#67c23a">
                        <Check/>
                      </el-icon>
                      <span>{{ t('personalCenter.viewData', {count: pkg.viewRecords}) }}</span>
                    </div>
                    <div class="feature-item" :class="{ 'disabled': pkg.level === 0 }">
                      <el-icon :color="pkg.level === 0 ? '#f56c6c' : '#67c23a'">
                        <component :is="pkg.level === 0 ? 'Close' : 'Check'"/>
                      </el-icon>
                      <span>{{
                          pkg.level === 0 ? t('personalCenter.exportData') : t('personalCenter.exportTimes', {count: pkg.exportQuota})
                        }}</span>
                    </div>
                    <div class="feature-item" :class="{ 'disabled': pkg.level === 0 }">
                      <el-icon :color="pkg.level === 0 ? '#f56c6c' : '#67c23a'">
                        <component :is="pkg.level === 0 ? 'Close' : 'Check'"/>
                      </el-icon>
                      <span>{{
                          pkg.level === 0 ? t('personalCenter.lookupFeature') : t('personalCenter.lookupTimes', {count: pkg.reverseLookup})
                        }}</span>
                    </div>
                    <div class="feature-item">
                      <el-icon :color="pkg.level >= 2 ? '#67c23a' : '#f56c6c'">
                        <component :is="pkg.level >= 2 ? 'Check' : 'Close'"/>
                      </el-icon>
                      <span>{{
                          pkg.level >= 2 ? t('personalCenter.prioritySupport') : t('personalCenter.standardSupport')
                        }}</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 资料设置标签页 -->
          <div v-if="activeTab === 'profileSettings'" class="tab-section">
            <div v-if="!isLoggedIn" class="login-prompt">
              <el-icon :size="64" class="prompt-icon">
                <Lock/>
              </el-icon>
              <p class="prompt-title">{{ t('personalCenter.needLogin') }}</p>
              <p class="prompt-desc">{{ t('personalCenter.pleaseLoginToEditProfile') }}</p>
              <el-button type="primary" @click="goToLogin">{{ t('personalCenter.goToLogin') }}</el-button>
            </div>

            <template v-else>
              <div class="profile-settings-container">
                <!-- 左侧导航 -->
                <div class="profile-settings-nav">
                  <div
                      class="nav-item"
                      :class="{ 'active': profileSettingsTab === 'userInfo' }"
                      @click="profileSettingsTab = 'userInfo'"
                  >
                    <el-icon>
                      <User/>
                    </el-icon>
                    <span>{{ t('personalCenter.userInfo') }}</span>
                  </div>
                  <div
                      class="nav-item"
                      :class="{ 'active': profileSettingsTab === 'security' }"
                      @click="profileSettingsTab = 'security'"
                  >
                    <el-icon>
                      <Lock/>
                    </el-icon>
                    <span>{{ t('personalCenter.security') }}</span>
                  </div>
                </div>

                <!-- 右侧内容区 -->
                <div class="profile-settings-content">
                  <!-- 个人资料 -->
                  <div v-if="profileSettingsTab === 'userInfo'" class="settings-panel">
                    <div class="panel-header">
                      <h3>{{ t('personalCenter.userInfo') }}</h3>
                      <p class="panel-desc">{{ t('personalCenter.userInfoDesc') }}</p>
                    </div>

                    <el-card class="profile-card" shadow="hover">
                      <div class="profile-info">
                        <div class="info-form">
                          <el-form
                              :model="userInfo"
                              label-position="top"
                              class="user-form"
                          >
                            <el-form-item :label="t('personalCenter.username')">
                              <div class="form-input-group">
                                <el-input v-model="userInfo.username" :placeholder="t('personalCenter.enterUsername')"/>
                              </div>
                            </el-form-item>

                            <el-form-item :label="t('personalCenter.phoneNumber')">
                              <div class="form-input-group">
                                <el-input v-model="userInfo.phone" :placeholder="t('personalCenter.enterPhoneNumber')"
                                          disabled/>
                              </div>
                            </el-form-item>

                            <el-form-item>
                              <el-button type="primary" @click="handleUpdateUserInfo">{{
                                  t('personalCenter.saveChanges')
                                }}
                              </el-button>
                              <el-button @click="resetUserInfo">{{ t('personalCenter.reset') }}</el-button>
                            </el-form-item>
                          </el-form>
                        </div>
                      </div>
                    </el-card>
                  </div>

                  <!-- 安全设置 -->
                  <div v-if="profileSettingsTab === 'security'" class="settings-panel">
                    <div class="panel-header">
                      <h3>{{ t('personalCenter.security') }}</h3>
                      <p class="panel-desc">{{ t('personalCenter.securityDesc') }}</p>
                    </div>

                    <el-card class="security-card" shadow="hover">
                      <div class="security-section">
                        <div class="section-header">
                          <h4>{{ t('personalCenter.passwordChange') }}</h4>
                          <p class="section-desc">{{ t('personalCenter.passwordChangeDesc') }}</p>
                        </div>

                        <el-form
                            ref="passwordFormRef"
                            :model="passwordForm"
                            :rules="passwordRules"
                            label-position="top"
                            class="password-form"
                        >
                          <el-form-item :label="t('personalCenter.currentPassword')" prop="currentPassword">
                            <el-input
                                v-model="passwordForm.currentPassword"
                                type="password"
                                :placeholder="t('personalCenter.enterCurrentPassword')"
                                show-password
                            />
                          </el-form-item>

                          <el-row :gutter="20">
                            <el-col :span="12">
                              <el-form-item :label="t('personalCenter.newPassword')" prop="newPassword">
                                <el-input
                                    v-model="passwordForm.newPassword"
                                    type="password"
                                    :placeholder="t('personalCenter.enterNewPassword')"
                                    show-password
                                />
                              </el-form-item>
                            </el-col>
                            <el-col :span="12">
                              <el-form-item :label="t('personalCenter.confirmPassword')" prop="confirmPassword">
                                <el-input
                                    v-model="passwordForm.confirmPassword"
                                    type="password"
                                    :placeholder="t('personalCenter.confirmNewPassword')"
                                    show-password
                                />
                              </el-form-item>
                            </el-col>
                          </el-row>

                          <el-form-item class="form-actions">
                            <el-button type="primary" @click="submitPasswordChange" :loading="passwordLoading">
                              {{ t('personalCenter.confirmChange') }}
                            </el-button>
                            <el-button @click="resetPasswordForm">{{ t('personalCenter.reset') }}</el-button>
                          </el-form-item>
                        </el-form>
                      </div>

                      <el-divider/>

                      <div class="security-section">
                        <div class="section-header">
                          <h4>{{ t('personalCenter.phoneBinding') }}</h4>
                          <p class="section-desc">{{ t('personalCenter.phoneBindingDesc') }}</p>
                        </div>

                        <div class="security-item">
                          <div class="security-info">
                            <el-icon class="security-icon">
                              <Phone/>
                            </el-icon>
                            <div class="security-text">
                              <div class="security-title">{{ t('personalCenter.boundPhone') }}</div>
                              <div class="security-value">{{ userInfo.phone }}</div>
                            </div>
                          </div>
                        </div>
                      </div>
                    </el-card>
                  </div>
                </div>
              </div>
            </template>
          </div>

          <!-- 推广返佣及联系客服标签页 -->
          <div v-if="activeTab === 'promotion'" class="tab-section promotion-section">
            <div class="profile-settings-container">
              <!-- 左侧导航 -->
              <div class="profile-settings-nav">
                <div
                    class="nav-item"
                    :class="{ 'active': promotionSettingsTab === 'promotionSystem' }"
                    @click="promotionSettingsTab = 'promotionSystem'"
                >
                  <el-icon>
                    <Promotion/>
                  </el-icon>
                  <span>{{ t('personalCenter.promotionRebate') }}</span>
                </div>
                <div
                    class="nav-item"
                    :class="{ 'active': promotionSettingsTab === 'customerService' }"
                    @click="promotionSettingsTab = 'customerService'"
                >
                  <el-icon>
                    <Service/>
                  </el-icon>
                  <span>{{ t('personalCenter.customerService') }}</span>
                </div>
              </div>

              <!-- 右侧内容区 -->
              <div class="profile-settings-content">
                <!-- 推广系统内容 -->
                <div v-if="promotionSettingsTab === 'promotionSystem'" class="settings-panel">
                  <div class="panel-header">
                    <h3>{{ t('personalCenter.promotionSystem') }}</h3>
                    <p class="panel-desc">{{ t('personalCenter.promotionSystemDesc') }}</p>
                  </div>

                  <el-card class="profile-card" shadow="hover">
                    <!-- 推广系统部分 -->
                    <div class="promotion-info">
                      <div class="promotion-description">
                        <p>{{ t('personalCenter.promotionShareDesc') }}</p>
                      </div>

                      <div class="promotion-link-box">
                        <div class="link-header">{{ t('personalCenter.promotionLink') }}</div>
                        <div class="link-content">
                          <el-input
                              v-model="promotionLink"
                              readonly
                              class="promotion-input"
                          >
                            <template #append>
                              <el-button @click="copyPromotionLink">{{ t('personalCenter.copy') }}</el-button>
                            </template>
                          </el-input>
                        </div>
                      </div>
                    </div>
                  </el-card>
                </div>

                <!-- 专属客服内容 -->
                <div v-if="promotionSettingsTab === 'customerService'" class="settings-panel">
                  <div class="panel-header">
                    <h3>{{ t('personalCenter.customerService') }}</h3>
                    <p class="panel-desc">{{ t('personalCenter.scanQrcode') }}</p>
                  </div>

                  <el-card class="profile-card" shadow="hover" v-loading="customerServiceLoading">
                    <div class="service-container">
                      <div v-if="customerServiceInfo" class="qrcode-container">
                        <img :src="customerServiceInfo.qrcodeUrl" :alt="t('personalCenter.customerService')"
                             class="customer-qrcode"/>
                        <p class="qrcode-hint">{{ t('personalCenter.wechatId') }}: {{
                            customerServiceInfo.wechatId
                          }}</p>
                        <div class="service-desc" v-if="customerServiceInfo.description">
                          <div v-html="customerServiceInfo.description"></div>
                        </div>
                      </div>
                      <div v-else class="empty-service">
                        <el-empty :description="t('personalCenter.noCustomerService')"/>
                      </div>
                    </div>
                  </el-card>
                </div>
              </div>
            </div>
          </div>

          <!-- 功能服务标签页 -->
          <div v-if="activeTab === 'functionService'" class="tab-section">
            <div class="section-title fancy-title">{{ t('personalCenter.servicesTitle') }}</div>

            <!-- 邮件套餐部分 -->
            <div class="section-container">
              <div class="section-header">
                <div class="section-title-wrapper">
                  <h3 class="section-title-text">{{ t('personalCenter.emailPackagesTitle') }}</h3>
                  <el-button type="primary" size="small" @click="fetchEmailPackages" :loading="emailLoading">
                    <el-icon>
                      <Refresh/>
                    </el-icon>
                    {{ t('personalCenter.refreshPackages') }}
                  </el-button>
                </div>

                <!-- 套餐说明 -->
                <div class="package-description">
                  <div class="description-title">{{ t('personalCenter.packageDescriptionTitle') }}</div>
                  <ul class="description-list">
                    <li>
                      <el-icon color="#67c23a">
                        <Check/>
                      </el-icon>
                      {{ t('personalCenter.packageIntro1') }}
                    </li>
                    <li>
                      <el-icon color="#67c23a">
                        <Check/>
                      </el-icon>
                      {{ t('personalCenter.packageIntro2') }}
                    </li>
                    <li>
                      <el-icon color="#67c23a">
                        <Check/>
                      </el-icon>
                      {{ t('personalCenter.packageIntro3') }}
                    </li>
                    <li>
                      <el-icon color="#67c23a">
                        <Check/>
                      </el-icon>
                      {{ t('personalCenter.packageIntro4') }}
                    </li>
                  </ul>
                </div>
              </div>

              <div v-loading="emailLoading" class="package-cards">
                <!-- 使用v-for动态渲染邮件套餐 -->
                <div v-for="pkg in emailPackages" :key="pkg.id" class="package-card">
                  <div class="package-tag" :class="{
                    'package-a': pkg.level === 1,
                    'package-b': pkg.level === 2, 
                    'package-c': pkg.level === 3, 
                    'package-d': pkg.level === 4
                  }">
                    {{ t('personalCenter.packageLabel', {label: String.fromCharCode(64 + pkg.level)}) }}
                  </div>
                  <div class="package-type">{{ pkg.name }}</div>
                  <div class="package-price">{{
                      t('personalCenter.packagePricePerUse', {price: pkg.price.toFixed(2)})
                    }}
                  </div>
                  <div class="price-underline"></div>

                  <!-- 套餐内容 -->
                  <div class="package-content">
                    <div class="content-item">
                      <el-icon color="#67c23a">
                        <Check/>
                      </el-icon>
                      <span class="highlight">{{
                          t('personalCenter.packageEmails', {count: pkg.emailCount.toLocaleString()})
                        }}</span>
                    </div>

                    <!-- 显示有效期 -->
                    <div class="content-item">
                      <el-icon color="#67c23a">
                        <Check/>
                      </el-icon>
                      <span>
                        {{
                          pkg.duration > 0 ? t('personalCenter.packageValidDays', {days: pkg.duration}) : t('personalCenter.packageValidForever')
                        }}
                      </span>
                    </div>

                    <!-- 套餐描述 -->
                    <div class="content-item">
                      <el-icon color="#67c23a">
                        <Check/>
                      </el-icon>
                      <span>{{ pkg.description || t('personalCenter.professionalEmailService') }}</span>
                    </div>

                    <div class="content-item">
                      <el-icon :color="pkg.level >= 2 ? '#67c23a' : '#f56c6c'">
                        <component :is="pkg.level >= 2 ? 'Check' : 'Close'"/>
                      </el-icon>
                      <span>{{
                          pkg.level >= 2 ? t('personalCenter.prioritySupport') : t('personalCenter.standardSupport')
                        }}</span>
                    </div>
                  </div>

                  <div class="package-footer">
                    <el-button type="primary" @click="handleBuyPackage(pkg)" :disabled="emailPurchaseLoading">
                      {{ t('personalCenter.buyNow') }}
                    </el-button>
                  </div>
                </div>
              </div>

              <!-- 没有套餐时的提示 -->
              <div v-if="emailPackages.length === 0 && !emailLoading" class="empty-package">
                <el-empty :description="t('personalCenter.noPackages')" :image-size="100">
                  <template #description>
                    <p>{{ t('personalCenter.noPackagesDesc') }}</p>
                  </template>
                  <el-button type="primary" @click="fetchEmailPackages">{{
                      t('personalCenter.refreshPackagesBtn')
                    }}
                  </el-button>
                </el-empty>
              </div>
            </div>
          </div>
        </div>

        <!-- 购买导出次数对话框 -->
        <el-dialog
            :title="t('personalCenter.buyExportTitle')"
            v-model="showBuyExportDialog"
            width="500px"
        >
          <el-form ref="buyExportFormRef" :model="buyExportForm" label-width="120px">
            <el-form-item :label="t('personalCenter.buyQuantity')" prop="amount">
              <el-input-number v-model="buyExportForm.amount" :min="1" :precision="0" style="width: 200px"/>
            </el-form-item>
            <el-form-item :label="t('personalCenter.unitPrice')">
              <span>{{ exportUnitPrice }} {{ t('personalCenter.unitPrice.unit') }} </span>
            </el-form-item>
            <el-form-item :label="t('personalCenter.totalPrice')">
              <span>{{ buyExportForm.amount * exportUnitPrice }} {{ t('personalCenter.unitPrice.yuan') }} </span>
            </el-form-item>
          </el-form>
          <template #footer>
            <div class="dialog-footer">
              <el-button @click="showBuyExportDialog = false">{{ t('common.cancel') }}</el-button>
              <el-button type="primary" @click="submitBuyExport" :loading="buyExportLoading">
                {{ t('personalCenter.confirmPurchase') }}
              </el-button>
            </div>
          </template>
        </el-dialog>

        <!-- 购买查看更多次数对话框 -->
        <el-dialog
            :title="t('personalCenter.buySearchTitle')"
            v-model="showBuySearchQuotaDialog"
            width="500px"
        >
          <el-form ref="buySearchQuotaFormRef" :model="buySearchQuotaForm" label-width="120px">
            <el-form-item :label="t('personalCenter.buyQuantity')" prop="amount">
              <el-input-number v-model="buySearchQuotaForm.amount" :min="1" :precision="0" style="width: 200px"/>
            </el-form-item>
            <el-form-item :label="t('personalCenter.unitPrice')">
              <span>{{ searchQuotaUnitPrice }} {{ t('personalCenter.unitPrice.unit') }}</span>
            </el-form-item>
            <el-form-item :label="t('personalCenter.totalPrice')">
              <span>{{ buySearchQuotaForm.amount * searchQuotaUnitPrice }} {{
                  t('personalCenter.unitPrice.yuan')
                }} </span>
            </el-form-item>
          </el-form>
          <template #footer>
            <div class="dialog-footer">
              <el-button @click="showBuySearchQuotaDialog = false">{{ t('common.cancel') }}</el-button>
              <el-button type="primary" @click="submitBuySearchQuota" :loading="buySearchQuotaLoading">
                {{ t('personalCenter.confirmPurchase') }}
              </el-button>
            </div>
          </template>
        </el-dialog>

        <!-- 支付对话框 -->
        <el-dialog
            :title="t('personalCenter.payTitle')"
            v-model="showPaymentDialog"
            width="400px"
            @closed="handleClosePaymentDialog"
        >
          <div class="payment-form">
            <div v-html="paymentFormHtml"></div>
          </div>
          <template #footer>
            <div class="dialog-footer">
              <el-button @click="showPaymentDialog = false">{{ t('common.cancel') }}</el-button>
              <el-button type="primary" @click="handleClosePaymentDialog">{{
                  t('personalCenter.confirmPay')
                }}
              </el-button>
            </div>
          </template>
        </el-dialog>

        <!-- 二维码对话框 -->
        <el-dialog
            :title="t('personalCenter.paymentQrTitle')"
            v-model="showQrCodeDialog"
            width="400px"
            @closed="handleClosePaymentDialog"
        >
          <div class="qrcode-container">
            <img :src="paymentQrCodeUrl" :alt="t('personalCenter.paymentQrTitle')" class="qrcode-image"/>
          </div>
          <template #footer>
            <div class="dialog-footer">
              <el-button @click="showQrCodeDialog = false">{{ t('common.close') }}</el-button>
              <el-button type="primary" @click="handleClosePaymentDialog">{{
                  t('personalCenter.confirmPay')
                }}
              </el-button>
            </div>
          </template>
        </el-dialog>

      </div>
    </div>
  </div>
</template>

<script setup>
import {computed, nextTick, onMounted, onUnmounted, ref, watch} from 'vue';
import {useRoute, useRouter} from 'vue-router';
import {ElMessage, ElMessageBox} from 'element-plus';
import {Check, Document, Lock, Phone, Promotion, Refresh, Service, User} from '@element-plus/icons-vue';
import {getCurrentLanguage, t} from '@/utils/i18n';
import MainHeader from '@/components/MainHeader.vue';
import SideMenu from '@/components/SideMenu.vue';
import {getAccountInfo, getTransactions, recharge} from '@/api/account'
import {updatePassword} from '@/api/auth'
import {getUserBalanceInfo, getUserInfo, updateUserInfo as apiUpdateUserInfo} from '@/api/user'
import {getUserVipStatus, getVipPackages, queryOrderStatus} from '@/api/vip'
import {getUserEmailBalance} from '@/api/email'
import {getCustomerServiceInfo} from '@/api/customerService'
import axios from 'axios'

const router = useRouter()
const route = useRoute()

// 基础状态变量
const isLoggedIn = ref(false)
const loading = ref(false)
const balanceLoading = ref(false)

// 用户信息相关变量
const userInfo = ref({
  username: '',
  phone: '',
  email: '',
  memberLevel: 0,
  vipExpireDate: null,
  searchQuota: 0
})

// 标签页配置
const tabs = [
  {name: 'myAccount', label: '我的账户', translationKey: 'personalCenter.myAccount'},
  {name: 'memberCenter', label: '会员中心', translationKey: 'personalCenter.memberCenter'},
  {name: 'promotion', label: '推广返佣及联系客服', translationKey: 'personalCenter.promotion'},
  {name: 'profileSettings', label: '资料设置', translationKey: 'personalCenter.profileSettings'},
  {name: 'functionService', label: '功能服务', translationKey: 'personalCenter.functionService'}
]
const activeTab = ref('profileSettings')

// 密码表单相关变量
const passwordFormRef = ref(null)
const passwordLoading = ref(false)
const passwordForm = ref({
  currentPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 充值表单验证规则
const rechargeRules = {
  amount: [
    {required: true, message: '请输入充值金额', trigger: 'blur'},
    {type: 'number', min: 1, message: '充值金额必须大于0', trigger: 'blur'}
  ]
}

// 交易记录相关变量
const transactions = ref([])
const transactionsLoading = ref(false)
const transactionType = ref('')

// VIP相关变量
const vipPackages = ref([])
const vipLoading = ref(false)
const vipPurchaseLoading = ref(false)
const vipExpireDate = ref(null)
const vipDaysLeft = ref(null)

// 邮件套餐相关变量
const emailPackages = ref([])
const emailLoading = ref(false)
const emailPurchaseLoading = ref(false)
const emailBalance = ref(0)

// 账户相关数据
const accountInfo = ref({
  balance: '0.00',
  vipExpireDate: null,
  searchQuota: 0,
  rechargeTotal: 0,
  consumptionTotal: 0
})

// 用户余额数据
const userBalances = ref({
  memberLevel: 0,
  memberLevelText: '免费版',
  vipExpireDate: null,
  exportQuota: 0,
  viewMoreQuota: 5,
  cashBalance: 0,
  exportQuotaRemaining: 0,
  viewPagesRemaining: 5,
  reverseLookupRemaining: 0,
  emailSendRemaining: 0,
  emailPackageLevel: 0,
  emailPackageName: '无套餐',
  updatedAt: null
})

// 购买相关变量
const showBuyExportDialog = ref(false)
const showBuySearchQuotaDialog = ref(false)
const exportUnitPrice = ref(5)
const searchQuotaUnitPrice = ref(3)
const buyExportForm = ref({
  amount: 1
})
const buySearchQuotaForm = ref({
  amount: 1
})
const buyExportLoading = ref(false)
const buySearchQuotaLoading = ref(false)
const buyExportFormRef = ref(null)
const buySearchQuotaFormRef = ref(null)

// 短信费率相关数据
const rateSearchQuery = ref('')
const showAllCountries = ref(false)

// 分页相关变量
const pageSize = ref(10)
const currentPage = ref(1)

// 客服信息相关变量
const customerServiceInfo = ref(null)
const customerServiceLoading = ref(false)

// 计算VIP剩余天数
const calculateVipDaysLeft = () => {
  if (!vipExpireDate.value) return null;

  const today = new Date();
  const expireDate = new Date(vipExpireDate.value);
  const diffTime = expireDate - today;
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));

  return diffDays > 0 ? diffDays : 0;
};

// 获取用户VIP到期日期信息
const fetchVipExpireDate = () => {
  if (userInfo.value.memberLevel > 0) {
    vipExpireDate.value = userBalances.value.vipExpireDate;
    vipDaysLeft.value = calculateVipDaysLeft();
  } else {
    vipExpireDate.value = null;
    vipDaysLeft.value = null;
  }
};

// 在获取用户信息后，获取VIP到期日期
// watch(() => userInfo.value.memberLevel, (newLevel) => {
//   fetchUserBalance();
// });

// 更新获取用户信息的函数
// 获取用户信息
const fetchUserInfo = async () => {
  try {
    // 调用API获取用户信息
    const res = await getUserInfo();
    const balanceRes = await getUserBalanceInfo();
    if (res && res.code === 200 && res.data && balanceRes && balanceRes.code === 200 && balanceRes.data) {
      // 将后端数据映射到前端显示所需的格式
      userInfo.value = {
        username: res.data.username,
        phone: res.data.phone,
        email: res.data.email,
        // 检查字段名称，后端可能使用下划线命名法或驼峰命名法
        memberLevel: (balanceRes.data.vipLevel ?? balanceRes.data.vip_level ?? 0),
        // balance字段从"账户余额"改为"剩余导出次数"
        balance: (balanceRes.data.exportQuotaRemaining ?? 0),
        // search_quota字段从"剩余搜索次数"改为"剩余查看更多次数"
        searchQuota: (balanceRes.data.viewRecordsRemaining ?? balanceRes.data.view_records_remaining ?? 0)
      };

      // 保存用户信息到localStorage，以便其他页面使用
      try {
        localStorage.setItem('userInfo', JSON.stringify(userInfo.value));
      } catch (e) {

      }

      // 更新用户余额数据
      userBalances.value = {
        memberLevel: userInfo.value.memberLevel,
        memberLevelText: getMemberLevelText(userInfo.value.memberLevel),
        exportQuota: userInfo.value.balance,
        viewMoreQuota: userInfo.value.searchQuota,
        cashBalance: userInfo.value.balance,
        exportQuotaRemaining: userInfo.value.balance,
        viewPagesRemaining: userInfo.value.searchQuota,
        reverseLookupRemaining: userInfo.value.searchQuota,
        emailSendRemaining: userInfo.value.searchQuota,
        emailPackageLevel: userInfo.value.memberLevel,
        updatedAt: new Date()
      };

      // 获取用户的VIP到期信息
      // fetchVipExpireDate();

      return true;
    } else {

      // 显示错误消息
      const errorMsg = res && res.msg ? res.msg : '服务器未返回数据';
      if (getCurrentLanguage() === 'zh') {
        ElMessage.error('获取用户信息失败: ' + errorMsg);
      } else {
        ElMessage.error('Failed to get user information');
      }

      // 如果是认证问题，提示用户重新登录
      if (res && (res.code === 401 || res.code === 403 || (res.msg && res.msg.includes('用户不存在')))) {
        if (getCurrentLanguage() === 'zh') {
          ElMessage.warning('登录信息已失效，请重新登录');
        } else {
          ElMessage.warning('Login information has expired, please log in again');
        }
        // 清除token
        localStorage.removeItem('token');
        setTimeout(() => {
          router.push('/login');
        }, 1500);
      }

      return false;
    }
  } catch (error) {

    // 显示错误消息
    if (getCurrentLanguage() === 'zh') {
      ElMessage.error('获取用户信息失败: ' + (error.message || error.response?.data?.message || '未知错误'));
    } else {
      ElMessage.error('Failed to get user information');
    }

    // 如果是401或403错误，可能是token失效，尝试重新登录
    if (error.response && (error.response.status === 401 || error.response.status === 403)) {
      if (getCurrentLanguage() === 'zh') {
        ElMessage.warning('登录信息已失效，请重新登录');
      } else {
        ElMessage.warning('Login information has expired, please log in again');
      }
      // 清除token
      localStorage.removeItem('token');
      setTimeout(() => {
        router.push('/login');
      }, 1500);
    }

    return false;
  }
};

// 更新单个字段
const updateField = async (fieldName) => {
  try {
    if (!fieldName || !userInfo.value[fieldName]) {
      if (getCurrentLanguage() === 'zh') {
        ElMessage.warning('请输入有效的' + getFieldLabel(fieldName));
      } else {
        ElMessage.warning('Please enter a valid ' + getFieldLabel(fieldName));
      }
      return;
    }

    const updateData = {};
    updateData[fieldName] = userInfo.value[fieldName];
    if (getCurrentLanguage() === 'zh') {
      ElMessage.info(`正在更新${getFieldLabel(fieldName)}...`);
    } else {
      ElMessage.info(`Updating ${getFieldLabel(fieldName)}...`);
    }

    const res = await apiUpdateUserInfo(updateData);

    if (res.code === 200) {
      if (getCurrentLanguage() === 'zh') {
        ElMessage.success(getFieldLabel(fieldName) + '更新成功');
      } else {
        ElMessage.success('updated successfully');
      }
      // 成功后统一刷新用户信息与余额，避免使用未定义的 balanceRes
      await fetchUserInfo();
    } else {
      if (getCurrentLanguage() === 'zh') {
        ElMessage.error(res.msg || '更新失败');
      } else {
        ElMessage.error('Failed to update ');
      }
      // 恢复之前的值
      await fetchUserInfo();
    }
  } catch (error) {
    if (getCurrentLanguage() === 'zh') {
      ElMessage.error('更新失败: ' + (error.message || error.response?.data?.message || '未知错误'));
    } else {
      ElMessage.error('Failed to update ')
    }
    // 发生错误时重新获取用户信息
    await fetchUserInfo();
  }
};

// 获取字段显示名
const getFieldLabel = (fieldName) => {
  const labels = {
    username: '用户名',
    phone: '手机号码',
    email: '邮箱'
  };
  return labels[fieldName] || fieldName;
};

// 会员等级文本转换
const getMemberLevelText = (level) => {
  const levelMap = {
    0: '免费版',
    1: '初级VIP',
    2: '高级VIP',
    3: '尊享VIP'
  }
  return levelMap[level] || '未知等级'
}

// 邮件套餐等级文本转换
const getEmailPackageLevelText = (level) => {
  // 如果level为null或undefined，返回默认值
  if (level === null || level === undefined) {
    return '无套餐';
  }

  // 套餐等级映射表
  const levelMap = {
    0: '无套餐',
    1: '套餐A',
    2: '套餐B',
    3: '套餐C',
    4: '套餐D',
    'A': '套餐A',
    'B': '套餐B',
    'C': '套餐C',
    'D': '套餐D'
  };

  // 检查是否是有效的套餐等级
  const levelKey = String(level).toUpperCase();
  return levelMap[level] || levelMap[levelKey] || `套餐${level}`;
}

// 账户相关方法
const fetchAccountInfo = async () => {
  try {
    const res = await getAccountInfo()
    if (res.data) {
      accountInfo.value = res.data
    }
  } catch (error) {
    if (getCurrentLanguage() === 'zh') {
      ElMessage.error('获取账户信息失败')
    } else {
      ElMessage.error('Failed to get account information')
    }
  }
}

// 获取用户详细余额信息
const fetchUserBalance = async () => {
  try {
    balanceLoading.value = true
    const res = await getUserBalanceInfo()
    if (res.code === 200 && res.data) {
      // 确保每个字段都有默认值，防止undefined
      const safeData = {
        vipLevel: res.data.vipLevel ?? res.data.memberLevel ?? 0,
        vipExpireDate: res.data.vipExpireTime ?? null,
        memberLevelText: res.data.memberLevelText ?? getMemberLevelText(res.data.vipLevel || 0),
        viewRecordsRemaining: res.data.viewRecordsRemaining ?? res.data.searchQuota ?? 5,
        exportQuotaRemaining: res.data.exportQuotaRemaining ?? 0,
        reverseLookupRemaining: res.data.reverseLookupRemaining ?? 0,
        emailSendRemaining: res.data.emailSendRemaining ?? 0,
        emailPackageLevel: res.data.emailPackageLevel ?? 0,
        emailPackageName: res.data.emailPackageName ?? '无套餐',
        updatedAt: res.data.updatedAt ?? new Date().toISOString()
      }

      // 更新userBalances对象
      userBalances.value = {
        memberLevel: safeData.vipLevel,
        vipExpireDate: safeData.vipExpireDate,
        memberLevelText: safeData.memberLevelText,
        exportQuota: safeData.exportQuotaRemaining,
        viewMoreQuota: safeData.viewRecordsRemaining,
        cashBalance: 0, // 现金余额默认为0
        exportQuotaRemaining: safeData.exportQuotaRemaining,
        viewPagesRemaining: safeData.viewRecordsRemaining,
        reverseLookupRemaining: safeData.reverseLookupRemaining,
        emailSendRemaining: safeData.emailSendRemaining,
        emailPackageLevel: safeData.emailPackageLevel,
        emailPackageName: safeData.emailPackageName,
        updatedAt: safeData.updatedAt
      }

      fetchVipExpireDate();

      // 显示成功提示
      if (getCurrentLanguage() === 'zh') {
        ElMessage.success('余额数据刷新成功')
      } else {
        ElMessage.success('Balance data refresh success')
      }
    } else {
      if (getCurrentLanguage() === 'zh') {
        ElMessage.error('获取用户余额信息失败: ' + (res.msg || '未知错误'))
      } else {
        ElMessage.error('Failed to get user balance information')
      }
    }
  } catch (error) {
    if (getCurrentLanguage() === 'zh') {
      ElMessage.error('获取用户余额信息失败: ' + (error.message || '未知异常'))
    } else {
      ElMessage.error('Failed to get user balance information')
    }
  } finally {
    balanceLoading.value = false
  }
}

const fetchTransactions = async () => {
  try {
    transactionsLoading.value = true
    // 确保使用当前登录用户的所有可能标识信息
    const phone = userInfo.value?.phone

    // 添加请求参数
    const params = {
      phone: phone,
      limit: 100 // 获取更多记录
    }

    // 根据过滤条件添加参数 - 修复参数名
    if (transactionType.value) {
      // 使用正确的参数名称：recharge_type 而不是 rechargeType
      params.recharge_type = transactionType.value;
    }

    const res = await getTransactions(params)
    if (res.code === 200 && res.data) {
      // 将数据赋值给交易记录列表
      const records = Array.isArray(res.data) ? res.data : [];

      // 如果返回的是对象而不是数组，尝试提取records字段
      if (!Array.isArray(res.data) && res.data.records && Array.isArray(res.data.records)) {
        transactions.value = res.data.records;
        // 更新账户信息中的充值总额
        if (res.data.totalAmount !== undefined) {
          accountInfo.value.rechargeTotal = res.data.totalAmount;
        }
      } else {
        transactions.value = records;
      }

      // 遍历并处理数据字段，确保前端展示属性名与后端返回一致
      transactions.value = transactions.value.map(item => {
        // 尝试将下划线命名法转为驼峰命名法
        const processed = {...item};

        // 检查并转换充值类型字段
        if (item.recharge_type !== undefined && item.rechargeType === undefined) {
          processed.rechargeType = item.recharge_type;
        }

        // 检查并转换支付方式字段
        if (item.payment_method !== undefined && item.paymentMethod === undefined) {
          processed.paymentMethod = item.payment_method;
        }

        return processed;
      });

      // 如果数据为空，给出提示
      if (transactions.value.length === 0) {
        if (getCurrentLanguage() === 'zh') {
          ElMessage.info('暂无充值记录数据')
        } else {
          ElMessage.info('No recharge record data')
        }
      } else {
      }
    } else {
      if (getCurrentLanguage() === 'zh') {
        ElMessage.error(res.msg || '获取充值记录失败')
      } else {
        ElMessage.error('Failed to get recharge record')
      }
      transactions.value = []
    }
  } catch (error) {
    if (getCurrentLanguage() === 'zh') {
      ElMessage.error('获取充值记录失败: ' + (error.message || '未知错误'))
    } else {
      ElMessage.error('Failed to get recharge record')
    }
    transactions.value = []
  } finally {
    transactionsLoading.value = false
  }
}

const handleRecharge = async () => {
  try {
    rechargeLoading.value = true

    // 先检查登录状态
    if (!isLoggedIn.value) {
      if (getCurrentLanguage() === 'zh') {
        ElMessage.error('您尚未登录，请先登录后再充值')
      } else {
        ElMessage.error('Please log in first before recharging')
      }
      setTimeout(() => {
        router.push('/login')
      }, 1500)
      return
    }

    // 检查用户信息是否完整
    if (!userInfo.value || !userInfo.value.phone) {
      if (getCurrentLanguage() === 'zh') {
        ElMessage.error('用户信息不完整，请刷新页面或重新登录')
      } else {
        ElMessage.error('User information is incomplete, please refresh the page or log in again')
      }
      setTimeout(() => {
        fetchUserInfo()
      }, 1000)
      return
    }

    // 确保表单验证通过
    if (rechargeFormRef.value) {
      await rechargeFormRef.value.validate()
    }
    // 构建充值数据，只需要包含手机号作为用户标识
    const rechargeData = {
      ...rechargeForm.value,
      phone: userInfo.value.phone
    }

    // 如果后端需要额外的用户ID，使用从用户信息中获取的ID
    if (userInfo.value.id) {
      rechargeData.userId = userInfo.value.id;
    }

    // 调用充值API
    const res = await recharge(rechargeData)

    if (res.code === 200) {
      if (getCurrentLanguage() === 'zh') {
        ElMessage.success('充值成功')
      } else {
        ElMessage.success('Recharge successful')
      }
      // 刷新账户信息
      fetchAccountInfo()
      fetchTransactions()
      showRechargeDialog.value = false
    } else {
      if (getCurrentLanguage() === 'zh') {
        ElMessage.error(res.msg || '充值失败')
      } else {
        ElMessage.error('Recharge failed')
      }
    }
  } catch (error) {
    if (getCurrentLanguage() === 'zh') {
      ElMessage.error('充值失败: ' + (error.message || error.response?.data?.message || '未知错误'))
    } else {
      ElMessage.error('Recharge failed')
    }
  } finally {
    rechargeLoading.value = false
  }
}

// 格式化金额
const formatAmount = (amount) => {
  if (amount === null || amount === undefined) return '0.00'

  const num = parseFloat(amount)
  return (num >= 0 ? '+' : '') + num.toFixed(2)
}

// 日期格式化函数
const formatDate = (dateString) => {
  if (!dateString) return '--'

  try {
    const date = new Date(dateString)
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    }).replace(/\//g, '-')
  } catch (error) {
    return dateString
  }
}
// 检查登录状态
const verifyLoginStatus = async () => {
  if (!localStorage.getItem('token')) {
    isLoggedIn.value = false;
    if (getCurrentLanguage() === 'zh') {
      ElMessage.warning('您尚未登录，请先登录');
    } else {
      ElMessage.warning('Please log in first');
    }
    setTimeout(() => {
      router.push('/login');
    }, 1500);
    return false;
  }

  isLoggedIn.value = true;
  return true;
};

// 组件挂载时的初始化
onMounted(async () => {
  try {
    // 检查登录状态
    const loginStatus = await verifyLoginStatus();
    if (!loginStatus) {
      return;
    }
    // 先获取用户基本信息
    const userInfoSuccess = await fetchUserInfo();

    if (!userInfoSuccess) {
      isLoggedIn.value = false;
      return;
    }

    // 获取用户余额详情
    await fetchUserBalance();

    // 获取账户信息和交易记录
    await fetchAccountInfo();
    await fetchTransactions();

    // 然后获取VIP状态（包含会员等级和配额信息）
    // await fetchUserVipStatus();

    // 检查URL参数，如果有tab参数，则切换到对应的标签页
    if (route.query.tab) {
      const tabName = route.query.tab;
      if (tabs.some(tab => tab.name === tabName)) {
        activeTab.value = tabName;
      }
    }

  } catch (error) {
    if (getCurrentLanguage() === 'zh') {
      ElMessage.error('数据加载失败，请刷新页面重试');
    } else {
      ElMessage.error('Failed to load data, please refresh the page and try again');
    }
  }
});

// 组件销毁时移除事件监听
onUnmounted(() => {
  // 移除事件监听器
});

// 监听标签页变化，加载相应数据
watch(activeTab, async (newValue) => {
  if (!isLoggedIn.value) return;

  if (newValue === 'myAccount') {
    // 先获取用户信息，再获取余额，避免并发导致余额被覆盖
    await fetchUserInfo();
    await fetchUserBalance();
    // 账户信息与交易记录可并行
    await Promise.all([
      fetchAccountInfo(),
      fetchTransactions()
    ]);
  } else if (newValue === 'profileSettings') {
    await fetchUserInfo();
  } else if (newValue === 'memberCenter') {
    await fetchUserInfo();
    fetchVipPackages(); // 获取VIP套餐列表
  } else if (newValue === 'functionService') {
    // 切换到功能服务标签页时，加载邮件套餐信息
    fetchEmailPackages(); // 获取邮件套餐列表
    fetchEmailBalance(); // 获取邮件余额
  } else if (newValue === 'promotion') {
    // 切换到推广返佣及联系客服标签页时，设置默认子标签页
    promotionSettingsTab.value = 'promotionSystem';
    // 获取推广数据
    nextTick(() => {
      fetchPromotionData();
    });
  }
});

// 跳转到登录页
const goToLogin = () => {
  router.push('/login');
};

// 修改跳转到充值页面的函数
// 跳转到充值页面
// const goToRecharge = () => {
//   // 检查是否已登录
//   if (!isLoggedIn.value) {
//     if (getCurrentLanguage() === 'zh') {
//       ElMessage.warning('请先登录后再进行充值操作');
//     } else {
//       ElMessage.warning('Please log in first before recharging');
//     }
//     setTimeout(() => {
//       router.push('/login');
//     }, 1500);
//     return;
//   }
//
//   // 检查是否有用户信息
//   const userInfoStr = localStorage.getItem('userInfo');
//   if (!userInfoStr) {
//     // 如果localStorage中没有用户信息，尝试将当前userInfo保存到localStorage
//     if (userInfo.value && userInfo.value.phone) {
//       localStorage.setItem('userInfo', JSON.stringify(userInfo.value));
//     } else {
//       // 如果没有用户信息，先获取一次
//       if (getCurrentLanguage() === 'zh') {
//         ElMessage.info('正在获取用户信息，请稍候...');
//       } else {
//         ElMessage.info('Fetching user information, please wait...');
//       }
//       fetchUserInfo().then(success => {
//         if (success) {
//           router.push('/recharge');
//         } else {
//           if (getCurrentLanguage() === 'zh') {
//             ElMessage.error('获取用户信息失败，无法进行充值');
//           } else {
//             ElMessage.error('Failed to get user information, recharge operation is not allowed');
//           }
//         }
//       });
//       return;
//     }
//   }
//
//   // 有用户信息，直接跳转
//   try {
//     router.push('/recharge');
//   } catch (error) {
//     if (getCurrentLanguage() === 'zh') {
//       ElMessage.error('页面跳转失败，请刷新后重试');
//     } else {
//       ElMessage.error('Failed to redirect to recharge page, please refresh the page and try again');
//     }
//   }
// };

// 提交密码修改
const submitPasswordChange = () => {
  passwordFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        passwordLoading.value = true

        // 准备要发送的数据
        const passwordData = {
          currentPassword: passwordForm.value.currentPassword,
          newPassword: passwordForm.value.newPassword
        };
        // 调用API更新密码
        const response = await updatePassword(passwordData);

        if (getCurrentLanguage() === 'zh') {
          ElMessage.success('密码修改成功，请重新登录')
        } else {
          ElMessage.success('Password change success, please log in again')
        }

        // 退出登录
        localStorage.removeItem('token')
        setTimeout(() => {
          router.push('/login')
        }, 1500)
      } catch (error) {
        if (getCurrentLanguage() === 'zh') {
          ElMessage.error('密码修改失败: ' + (error.message || error.response?.data?.message || '未知错误'))
        } else {
          ElMessage.error('Failed to change password')
        }
      } finally {
        passwordLoading.value = false
      }
    }
  })
}

// 重置密码表单
const resetPasswordForm = () => {
  passwordFormRef.value.resetFields()
}

// 重置充值表单
const resetRechargeForm = () => {
  if (rechargeFormRef.value) {
    rechargeFormRef.value.resetFields()
  }
  // 手动重置表单数据
  rechargeForm.value = {
    amount: 100,
    description: '账户充值',
    payMethod: 'alipay'
  }
}

// 提交购买导出次数
const submitBuyExport = async () => {
  if (!buyExportFormRef.value) return

  await buyExportFormRef.value.validate(async (valid) => {
    if (!valid) return

    buyExportLoading.value = true
    try {
      // 调用API购买导出次数
      const res = await buyExportQuota(buyExportForm.value.amount)

      if (res.code === 200) {
        // 更新本地数据
        userInfo.value.balance += buyExportForm.value.amount
        // 更新用户余额数据
        userBalances.value.exportQuota = userInfo.value.balance
        if (getCurrentLanguage() === 'zh') {
          ElMessage.success('购买成功')
        } else {
          ElMessage.success('Purchase successful')
        }
        showBuyExportDialog.value = false
      } else {
        if (getCurrentLanguage() === 'zh') {
          ElMessage.error(res.msg || '购买失败')
        } else {
          ElMessage.error('Purchase failed')
        }
      }
    } catch (error) {
      if (getCurrentLanguage() === 'zh') {
        ElMessage.error('购买失败: ' + (error.message || error.response?.data?.message || '未知错误'))
      } else {
        ElMessage.error('Purchase failed')
      }
    } finally {
      buyExportLoading.value = false
    }
  })
}

// 提交购买查看更多次数
const submitBuySearchQuota = async () => {
  if (!buySearchQuotaFormRef.value) return

  await buySearchQuotaFormRef.value.validate(async (valid) => {
    if (!valid) return

    buySearchQuotaLoading.value = true
    try {
      // 调用API购买查看更多次数
      const res = await buySearchQuota(buySearchQuotaForm.value.amount)

      if (res.code === 200) {
        // 更新本地数据
        userInfo.value.searchQuota += buySearchQuotaForm.value.amount
        // 更新用户余额数据
        userBalances.value.viewMoreQuota = userInfo.value.searchQuota
        if (getCurrentLanguage() === 'zh') {
          ElMessage.success('购买成功')
        } else {
          ElMessage.success('Purchase successful')
        }
        showBuySearchQuotaDialog.value = false
      } else {
        if (getCurrentLanguage() === 'zh') {
          ElMessage.error(res.msg || '购买失败')
        } else {
          ElMessage.error('Purchase failed')
        }
      }
    } catch (error) {
      if (getCurrentLanguage() === 'zh') {
        ElMessage.error('购买失败: ' + (error.message || error.response?.data?.message || '未知错误'))
      } else {
        ElMessage.error('Purchase failed')
      }
    } finally {
      buySearchQuotaLoading.value = false
    }
  })
}

// 处理会员升级
const handleUpgrade = async (level) => {
  // 查找目标等级的套餐
  const targetPackage = vipPackages.value.find(p => p.level === level)
  if (!targetPackage) {
    if (getCurrentLanguage() === 'zh') {
      ElMessage.error('未找到对应的会员套餐')
    } else {
      ElMessage.error('Failed to find the corresponding VIP package')
    }
    return
  }

  // 显示确认对话框
  if (getCurrentLanguage() === 'zh') {
    ElMessageBox.confirm(
        ` 确定要升级到${targetPackage.name}？\n     价格：¥${targetPackage.price}\n     时长：${targetPackage.duration}个月\n     包含：导出${targetPackage.exportQuota}次，查看${targetPackage.viewRecords}页，反查${targetPackage.reverseLookup}次`,
        '升级会员',
        {
          confirmButtonText: '确认升级',
          cancelButtonText: '取消',
          type: 'info',
          dangerouslyUseHTMLString: true
        }
    ).then(() => {
      // 跳转到充值页面
      router.push({
        path: '/recharge',
        query: {
          packageId: targetPackage.id,
          packageName: targetPackage.name,
          amount: targetPackage.price,
          duration: targetPackage.duration,
          productType: 'VIP'
        }
      })
    }).catch(() => {
      ElMessage.info('取消升级')
    })
  } else {
    ElMessageBox.confirm(
        `Are you sure to upgrade to ${targetPackage.name}? \n     Price: ¥${targetPackage.price},\n     Duration: ${targetPackage.duration} months, \n     Includes: Export ${targetPackage.exportQuota} times`,
        'Upgrade member',
        {
          confirmButtonText: 'Confirm upgrade',
          cancelButtonText: 'Cancel',
          type: 'info',
          dangerouslyUseHTMLString: true
        }
    ).then(() => {
      // 跳转到充值页面
      router.push({
        path: '/recharge',
        query: {
          packageId: targetPackage.id,
          packageName: targetPackage.name,
          amount: targetPackage.price,
          duration: targetPackage.duration,
          productType: 'VIP'
        }
      })
    }).catch(() => {
      ElMessage.info('Cancel upgrade')
    })
  }
}

// 获取会员等级名称
const getLevelName = (level) => {
  const levelMap = {
    0: '免费版',
    1: '初级VIP',
    2: '高级VIP',
    3: '尊享VIP'
  };
  return levelMap[level] || '未知等级';
};

// 处理购买邮件套餐
const handleBuyPackage = (pkg) => {
  if (!isLoggedIn.value) {
    if (getCurrentLanguage() === 'zh') {
      ElMessage.warning('请先登录后操作')
    } else {
      ElMessage.warning('Please log in first before operation')
    }
    setTimeout(() => {
      router.push('/login')
    }, 1500)
    return
  }

  // 检查套餐列表是否已加载
  if (emailPackages.value.length === 0) {
    if (getCurrentLanguage() === 'zh') {
      ElMessage.warning('套餐列表尚未加载完成，请稍后再试')
    } else {
      ElMessage.warning('Email package list is not loaded yet, please try again later')
    }
    // 重新加载套餐列表
    fetchEmailPackages()
    return
  }

  // 显示确认对话框
  if (getCurrentLanguage() === 'zh') {
    ElMessageBox.confirm(
        `确定要购买邮件${pkg.name}（价格：¥${pkg.price}）吗？\n包含：${pkg.email_count}封邮件\n${pkg.duration > 0 ? `有效期：${pkg.duration}天` : '永久有效'}`,
        '购买套餐',
        {
          confirmButtonText: '确认购买',
          cancelButtonText: '取消',
          type: 'info',
          dangerouslyUseHTMLString: true
        }
    ).then(() => {
      // 跳转到充值页面
      router.push({
        path: '/recharge',
        query: {
          packageId: pkg.id,
          packageName: pkg.name,
          amount: pkg.price,
          emailCount: pkg.email_count,
          packageLevel: pkg.level,
          duration: pkg.duration,
          productType: 'EMAIL'
        }
      })
    }).catch(() => {
      ElMessage.info('取消购买')
    })
  } else {
    ElMessageBox.confirm(
        `Are you sure to buy the ${pkg.name} package (price: ¥${pkg.price})? \n Includes: ${pkg.email_count} emails, ${pkg.duration > 0 ? `Valid for ${pkg.duration} days` : 'Perpetual validity'}`,
        'Buy package',
        {
          confirmButtonText: 'Confirm purchase',
          cancelButtonText: 'Cancel',
          type: 'info',
          dangerouslyUseHTMLString: true
        }
    ).then(() => {
      // 跳转到充值页面
      router.push({
        path: '/recharge',
        query: {
          packageId: pkg.id,
          packageName: pkg.name,
          amount: pkg.price,
          emailCount: pkg.email_count,
          packageLevel: pkg.level,
          duration: pkg.duration,
          productType: 'EMAIL'
        }
      })
    }).catch(() => {
      ElMessage.info('Cancel purchase')
    })
  }
}

// 获取VIP套餐列表
const fetchVipPackages = async () => {
  try {
    vipLoading.value = true
    const res = await getVipPackages()
    if (res.code === 200 && res.data) {
      // 确保level字段为数字类型
      vipPackages.value = res.data.map(pkg => ({
        ...pkg,
        level: Number(pkg.level)  // 确保level是数字类型
      }))
    } else {

    }
  } catch (error) {
    if (getCurrentLanguage() === 'zh') {
      ElMessage.error('获取VIP套餐失败')
    } else {
      ElMessage.error('Failed to get VIP packages')
    }
  } finally {
    vipLoading.value = false
  }
}

// 根据套餐等级生成卡片样式
const getPlanCardStyle = (level) => {
  // 定义颜色方案，支持任意数量的等级
  const colorSchemes = [
    { bg: '#f5f5f5', border: '#e0e0e0' },      // level 0: 免费版
    { bg: '#fff2e8', border: '#ff9a32' },      // level 1: 初级VIP
    { bg: '#fff7e6', border: '#ff7e36' },      // level 2: 高级VIP
    { bg: '#e6f7ff', border: '#4e95ff' },      // level 3: 尊享VIP
    { bg: '#f0e6ff', border: '#9254de' },      // level 4: 钻石VIP
    { bg: '#e6f9ff', border: '#13c2c2' },      // level 5: 白金VIP
    { bg: '#fff1f0', border: '#ff4d4f' },      // level 6: 红金VIP
    { bg: '#fffbe6', border: '#faad14' }       // level 7: 黄金VIP
  ]

  const scheme = colorSchemes[level] || colorSchemes[colorSchemes.length - 1]
  return {
    borderColor: scheme.border,
    borderWidth: '2px'
  }
}

// 根据套餐等级生成标签样式
const getPlanTagStyle = (level) => {
  const tagSchemes = [
    { bg: '#f5f5f5', color: '#333' },          // level 0
    { bg: '#fff2e8', color: '#ff6a00' },       // level 1
    { bg: '#fff7e6', color: '#ff4500' },       // level 2
    { bg: '#e6f7ff', color: '#1a6eff' },       // level 3
    { bg: '#f0e6ff', color: '#722ed1' },       // level 4
    { bg: '#e6f9ff', color: '#13a8a8' },       // level 5
    { bg: '#fff1f0', color: '#ff4d4f' },       // level 6
    { bg: '#fffbe6', color: '#d48806' }        // level 7
  ]

  const scheme = tagSchemes[level] || tagSchemes[tagSchemes.length - 1]
  return {
    backgroundColor: scheme.bg,
    color: scheme.color
  }
}

// 根据套餐等级生成按钮样式
const getPlanButtonStyle = (level) => {
  const buttonSchemes = [
    { bg: 'linear-gradient(135deg, #999, #666)' },           // level 0
    { bg: 'linear-gradient(135deg, #ff9a32, #ff6a00)' },     // level 1
    { bg: 'linear-gradient(135deg, #ff7e36, #ff4500)' },     // level 2
    { bg: 'linear-gradient(135deg, #4e95ff, #1a6eff)' },     // level 3
    { bg: 'linear-gradient(135deg, #9254de, #722ed1)' },     // level 4
    { bg: 'linear-gradient(135deg, #13c2c2, #13a8a8)' },     // level 5
    { bg: 'linear-gradient(135deg, #ff4d4f, #ff7875)' },     // level 6
    { bg: 'linear-gradient(135deg, #faad14, #d48806)' }      // level 7
  ]

  const scheme = buttonSchemes[level] || buttonSchemes[buttonSchemes.length - 1]
  return {
    background: scheme.bg,
    border: 'none'
  }
}

// 获取用户VIP状态
const fetchUserVipStatus = async () => {
  try {
    if (!isLoggedIn.value) return
    const res = await getUserVipStatus()
    if (res.code === 200 && res.data) {
      // 更新VIP到期时间
      vipExpireDate.value = res.data.vipExpireTime
      vipDaysLeft.value = calculateVipDaysLeft()

      // 更新用户会员等级
      if (res.data.vipLevel !== undefined) {
        userInfo.value.memberLevel = res.data.vipLevel
        userBalances.value.memberLevel = res.data.vipLevel
        userBalances.value.memberLevelText = getMemberLevelText(res.data.vipLevel)
      }

      // 更新配额信息
      if (res.data.exportQuotaRemaining !== undefined) {
        userBalances.value.exportQuota = res.data.exportQuotaRemaining;
        userBalances.value.exportQuotaRemaining = res.data.exportQuotaRemaining;
      }

      if (res.data.viewPagesRemaining !== undefined) {
        userBalances.value.viewMoreQuota = res.data.viewPagesRemaining;
        userBalances.value.viewPagesRemaining = res.data.viewPagesRemaining;
      }

      if (res.data.reverseLookupRemaining !== undefined) {
        userBalances.value.reverseLookupRemaining = res.data.reverseLookupRemaining;
      }

      // 确保获取了完整的用户余额信息
      if (!userBalances.value.cashBalance || !userBalances.value.emailSendRemaining) {
        await fetchUserBalance();
      }
    }
  } catch (error) {

  }
}

// 获取邮件套餐列表
const fetchEmailPackages = async () => {
  emailLoading.value = true;
  try {
    const response = await axios.get('/api/email/packages');
    if (response.data.code === 200 && response.data.data) {
      // 直接使用后端返回的完整数据结构
      emailPackages.value = response.data.data;
    } else {
      if (getCurrentLanguage() === 'zh') {
        ElMessage.error('获取邮件套餐失败');
      } else {
        ElMessage.error('Failed to get email packages');
      }
    }
  } catch (error) {
    if (getCurrentLanguage() === 'zh') {
      ElMessage.error('获取邮件套餐失败');
    } else {
      ElMessage.error('Failed to get email packages');
    }
  } finally {
    emailLoading.value = false;
  }
};

// 获取邮件余额
const fetchEmailBalance = async () => {
  try {
    if (!isLoggedIn.value) return
    const res = await getUserEmailBalance()
    if (res.code === 200 && res.data) {
      // 从balance/info端点获取emailSendRemaining字段
      emailBalance.value = res.data.emailSendRemaining || 0
    }
  } catch (error) {

  }
}

// 获取交易状态对应的文本
const getStatusText = (status) => {
  if (status === null || status === undefined) return '未知';

  // 处理数字/字符串数字类型
  if (status === 0 || status === '0') {
    return '成功';
  }
  if (status === 1 || status === '1') {
    return '失败';
  }

  // 处理字符串类型
  const statusStr = String(status).toUpperCase();
  const statusMap = {
    'SUCCESS': '成功',
    'PENDING': '处理中',
    'FAILED': '失败',
    'CANCELLED': '已取消',
    'REFUNDED': '已退款',
    'PROCESSING': '处理中',
    '0': '成功',
    '1': '失败'
  };
  return statusMap[statusStr] || status.toString() || '未知';
};

// 获取交易状态对应的标签类型
const getStatusTagType = (status) => {
  if (status === null || status === undefined) return 'info';

  // 处理数字/字符串数字类型
  if (status === 0 || status === '0') {
    return 'success';
  }

  // 处理字符串类型
  const statusStr = status.toString().toUpperCase();
  const typeMap = {
    'SUCCESS': 'success',
    'PENDING': 'info',
    'FAILED': 'danger',
    'CANCELLED': 'warning',
    'REFUNDED': 'warning',
    'PROCESSING': 'info',
    '0': 'success',
    '1': 'danger'
  };
  return typeMap[statusStr] || 'info';
};

// 分页方法
const handleCurrentChange = (page) => {
  currentPage.value = page
}

const handleSizeChange = (size) => {
  pageSize.value = size
}

// 分页后的交易记录
const paginatedTransactions = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return transactions.value.slice(start, end)
})

// 获取充值类型对应的文本
const getRechargeTypeText = (type) => {
  if (!type) return '未知';

  // 统一转换为大写，以确保兼容性
  const upperType = type.toString().toUpperCase();

  const typeMap = {
    'VIP': 'VIP套餐',
    'EMAIL': '邮件套餐',
    'CUSTOM': '自定义充值',
    'EXPORT': '导出次数',
    'SEARCH': '查询次数'
  };
  return typeMap[upperType] || type || '未知';
};

// 获取充值类型对应的标签类型
const getRechargeTypeTagType = (type) => {
  if (!type) return 'info';

  // 统一转换为大写，以确保兼容性
  const upperType = type.toString().toUpperCase();

  const typeMap = {
    'VIP': 'success',
    'EMAIL': 'primary',
    'CUSTOM': 'warning',
    'EXPORT': 'danger',
    'SEARCH': 'info'
  };
  return typeMap[upperType] || 'info';
};

// 获取支付方式对应的文本
const getPaymentMethodText = (method) => {
  if (!method) return '未知';

  // 统一转换为大写，以确保兼容性
  const upperMethod = String(method).toUpperCase();

  const methodMap = {
    'WECHAT': '微信支付',
    'ALIPAY': '支付宝',
    'WECHATPAY': '微信支付',
    'ALIPAY_PAGE': '支付宝'
  };
  return methodMap[upperMethod] || method || '未知';
};

// 获取支付方式对应的标签类型
const getPaymentMethodTagType = (method) => {
  if (!method) return 'info';

  // 统一转换为大写，以确保兼容性
  const upperMethod = String(method).toUpperCase();

  const typeMap = {
    'WECHAT': 'success',
    'ALIPAY': 'primary',
    'WECHATPAY': 'success',
    'ALIPAY_PAGE': 'primary'
  };
  return typeMap[upperMethod] || 'info';
};

// 移除不必要的token控制台输出
const checkLoginStatus = () => {
  // 通过localStorage检查是否有token
  if (!localStorage.getItem('token')) {
    isLoggedIn.value = false;
    return false;
  }

  isLoggedIn.value = true;
  return true;
};
// 密码表单验证规则
if (getCurrentLanguage() === 'zh') {
  const passwordRules = {
    currentPassword: [
      {required: true, message: '请输入当前密码', trigger: 'blur'}
    ],
    newPassword: [
      {required: true, message: '请输入新密码', trigger: 'blur'},
      {min: 6, message: '密码长度不能小于6位', trigger: 'blur'}
    ],
    confirmPassword: [
      {required: true, message: '请再次输入新密码', trigger: 'blur'},
      {
        validator: (rule, value, callback) => {
          if (value !== passwordForm.value.newPassword) {
            callback(new Error('两次输入的密码不一致'))
          } else {
            callback()
          }
        },
        trigger: 'blur'
      }
    ]
  }
} else {
  const passwordRules = {
    currentPassword: [
      {required: true, message: 'Please enter current password', trigger: 'blur'}
    ],
    newPassword: [
      {required: true, message: 'Please enter new password', trigger: 'blur'},
      {min: 6, message: 'Password length cannot be less than 6 digits', trigger: 'blur'}
    ],
    confirmPassword: [
      {required: true, message: 'Please confirm new password', trigger: 'blur'},
      {
        validator: (rule, value, callback) => {
          if (value !== passwordForm.value.newPassword) {
            callback(new Error('The two passwords entered are inconsistent'))
          } else {
            callback()
          }
        },
        trigger: 'blur'
      }
    ]
  }
}

// 充值相关变量
const rechargeFormRef = ref(null)
const rechargeLoading = ref(false)
const rechargeForm = ref({
  amount: 100,
  description: '账户充值',
  payMethod: 'alipay'
})

// 监听路由变化，更新标签页
watch(() => route.query.tab, (newTab) => {
  if (newTab && tabs.some(tab => tab.name === newTab)) {
    activeTab.value = newTab;
  }
});

// 资料设置相关变量
const profileSettingsTab = ref('userInfo')
const userAvatar = ref('')

// 更新用户资料
const handleUpdateUserInfo = async () => {
  try {
    // 更新用户名
    if (userInfo.value.username) {
      await updateField('username');
    }
  } catch (error) {
    if (getCurrentLanguage() === 'zh') {
      ElMessage.error('更新失败，请稍后重试');
    } else {
      ElMessage.error('Failed to update, please try again later');
    }
  }
};

// 重置用户资料表单
const resetUserInfo = async () => {
  // 重置为原始数据
  await fetchUserInfo()
  if(getCurrentLanguage() === 'zh') {
    ElMessage.info('已重置个人资料')
  } else {
    ElMessage.info('Personal information has been reset')
  }
}

// 推广返佣相关变量
const promotionSettingsTab = ref('promotionSystem')
const promotionLink = ref('https://tg.shuhailinghang.cn/')
const promotionStats = ref({
  totalUsers: 0,
  totalOrders: 0,
  totalCommission: 0,
  availableCommission: 0
})
const commissionRecords = ref([])
const commissionLoading = ref(false)

// 复制推广链接
const copyPromotionLink = () => {
  const input = document.createElement('input')
  input.value = promotionLink.value
  document.body.appendChild(input)
  input.select()
  document.execCommand('copy')
  document.body.removeChild(input)
  if (getCurrentLanguage() === 'zh') {
    ElMessage.success('推广链接已复制到剪贴板')
  } else {
    ElMessage.success('Promotion link has been copied to clipboard')
  }

}

// 获取推广数据
const fetchPromotionData = async () => {
  // 这里应该调用后端API获取推广数据
  // 由于目前没有后端API，使用模拟数据
  promotionStats.value = {
    totalUsers: 12,
    totalOrders: 8,
    totalCommission: 240.5,
    availableCommission: 120.25
  }

  commissionLoading.value = true
  try {
    // 模拟API调用延迟
    await new Promise(resolve => setTimeout(resolve, 500))

    // 模拟佣金记录数据
    commissionRecords.value = [
      {
        orderId: 'ORD20230001',
        userName: '张三',
        orderAmount: 299,
        commission: 89.7,
        status: 'settled',
        createTime: '2023-05-15 14:30:22'
      },
      {
        orderId: 'ORD20230015',
        userName: '李四',
        orderAmount: 499,
        commission: 149.7,
        status: 'pending',
        createTime: '2023-06-20 09:15:43'
      },
      {
        orderId: 'ORD20230028',
        userName: '王五',
        orderAmount: 199,
        commission: 59.7,
        status: 'settled',
        createTime: '2023-07-05 16:45:10'
      }
    ]
  } catch (error) {
    if (getCurrentLanguage() === 'zh') {
      ElMessage.error('获取推广数据失败')
    } else {
      ElMessage.error('Failed to get promotion data')
    }
  } finally {
    commissionLoading.value = false
  }
}

// 监听标签页变化，生成二维码
watch(activeTab, (newTab) => {
  if (newTab === 'promotion') {
    // 在下一个DOM更新周期执行，确保DOM元素已渲染
    nextTick(() => {
      fetchPromotionData()
    })
  }
})

// 监听推广标签页变化
watch(promotionSettingsTab, (newTab) => {
  if (activeTab.value === 'promotion') {
    if (newTab === 'promotionSystem') {
      // 加载推广系统数据
      fetchPromotionData();
    } else if (newTab === 'customerService') {
      // 加载客服相关数据
      fetchCustomerServiceInfo();
    }
  }
})

// 获取客服信息
const fetchCustomerServiceInfo = async () => {
  customerServiceLoading.value = true
  try {
    const res = await getCustomerServiceInfo()
    if (res && res.code === 200) {
      customerServiceInfo.value = res.data
    } else {

    }
  } catch (error) {

  } finally {
    customerServiceLoading.value = false
  }
}

// 支付相关变量
const showPaymentDialog = ref(false)
const paymentFormHtml = ref('')
const showQrCodeDialog = ref(false)
const paymentQrCodeUrl = ref('')
const currentOrderNo = ref('')
const orderPollingTimer = ref(null)

// 开始轮询订单状态
const startOrderStatusPolling = (orderNo) => {
  // 清除之前的定时器
  if (orderPollingTimer.value) {
    clearInterval(orderPollingTimer.value)
  }

  // 设置新的定时器，每3秒查询一次订单状态
  orderPollingTimer.value = setInterval(async () => {
    try {
      const res = await queryOrderStatus(orderNo)
      if (res.code === 200 && res.data) {
        // 如果订单已支付
        if (res.data.status === 1) {
          // 清除定时器
          clearInterval(orderPollingTimer.value)
          orderPollingTimer.value = null

          // 清理支付元素和关闭对话框
          cleanupPaymentElements();

          // 提示用户并刷新数据
          if (getCurrentLanguage() === 'zh') {
            ElMessage.success('支付成功！')
          } else {
            ElMessage.success('Payment successful!')
          }
          fetchUserInfo()
          fetchUserVipStatus()
        }
      }
    } catch (error) {
      if (getCurrentLanguage() === 'zh') {
        ElMessage.error('订单状态查询失败，请稍后重试或者联系客服')
      } else {
        ElMessage.error('Failed to query order status, please try again later or contact customer service')
      }
    }
  }, 3000)
}

// 支付成功时清理DOM和定时器
const cleanupPaymentElements = () => {
  // 清理定时器
  if (orderPollingTimer.value) {
    clearInterval(orderPollingTimer.value);
    orderPollingTimer.value = null;
  }

  // 清理动态添加的支付表单元素
  const tempForms = document.querySelectorAll('div[data-payment-form]');
  tempForms.forEach(el => {
    document.body.removeChild(el);
  });

  // 关闭对话框
  showPaymentDialog.value = false;
  showQrCodeDialog.value = false;
};

// 关闭支付对话框时清除定时器和临时DOM元素
const handleClosePaymentDialog = () => {
  cleanupPaymentElements();
};

</script>

<style scoped>
.personal-center-container {
  height: 100%;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #ffffff;
  width: 100%;
}

.main-container {
  display: flex;
  flex: 1;
  height: 100%;
  min-height: calc(100vh - 60px);
  width: 100%;
}

.content {
  flex: 1;
  padding: 20px;
  height: 100%;
  overflow-y: auto;
  overflow-x: hidden;
  background-color: #ffffff;
}

/* 水平选项卡菜单样式 */
.horizontal-menu {
  display: flex;
  justify-content: center;
  background-color: #fff;
  margin-bottom: 20px;
  border-bottom: 1px solid #e0e0e0;
  width: 100%;
  padding: 0;
}

.menu-item {
  padding: 12px 20px;
  cursor: pointer;
  font-size: 14px;
  color: #666;
  position: relative;
  transition: all 0.3s ease;
}

.menu-item:hover {
  color: #409EFF;
}

.menu-item.active {
  color: #409EFF;
  font-weight: 500;
  border-bottom: 2px solid #409EFF;
}

.menu-item.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 30px;
  height: 2px;
  background: linear-gradient(90deg, #409EFF, #007BFF);
  border-radius: 2px;
  transition: all 0.3s ease;
}

/* 标签页内容样式 */
.tab-content {
  display: flex;
  flex-direction: column;
}

.tab-section {
  background-color: white;
  border-radius: 4px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

.section-container {
  background-color: white;
  border-radius: 4px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

.section-title {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin-bottom: 20px;
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 10px;
}

.section-tip {
  background-color: #f5f7fa;
  padding: 12px 15px;
  border-radius: 4px;
  color: #606266;
  font-size: 14px;
  margin-bottom: 20px;
}

.link {
  color: #409EFF;
  text-decoration: none;
  cursor: pointer;
}

.action-bar {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.filter-box {
  margin-left: auto;
}

.filter-select {
  width: 150px;
}

.table-container {
  margin-bottom: 20px;
  position: relative;
  min-height: 200px;
}

.data-table {
  width: 100%;
  border-collapse: collapse;
  table-layout: fixed;
}

.data-table th, .data-table td {
  padding: 12px 15px;
  text-align: left;
  border-bottom: 1px solid #ebeef5;
}

.data-table thead th {
  background-color: #f5f7fa;
  color: #909399;
  font-weight: 500;
}

.data-table tbody tr:hover {
  background-color: #f5f7fa;
}

.admin-tag {
  display: inline-block;
  padding: 2px 6px;
  background-color: #f56c6c;
  color: white;
  border-radius: 4px;
  font-size: 12px;
  margin-left: 8px;
}

.status-tag {
  display: inline-block;
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 12px;
}

.status-normal {
  background-color: #e1f3d8;
  color: #67c23a;
}

.status-disabled {
  background-color: #fde2e2;
  color: #f56c6c;
}

.pagination {
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

.page-info {
  margin-right: 15px;
  color: #606266;
  font-size: 14px;
}

/* 我的账户标签页样式 */
.account-overview {
  margin-bottom: 30px;
}

.account-cards {
  display: flex;
  gap: 20px;
}

.account-card {
  flex: 1;
  display: flex;
  align-items: center;
  padding: 20px;
  background-color: #ecf5ff;
  border-radius: 4px;
  border-left: 3px solid #409EFF;
}

.card-icon {
  width: 50px;
  height: 50px;
  background-color: #409EFF;
  border-radius: 50%;
  margin-right: 15px;
}

.wallet-icon {
  background-color: #409EFF;
}

.search-icon {
  background-color: #67c23a;
}

.card-info {
  flex: 1;
}

.card-amount {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  margin-bottom: 5px;
}

.card-label {
  color: #606266;
  font-size: 14px;
}

.recharge-action-bar {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 15px;
}

.charge-notice {
  background-color: #f8f9fa;
  border-radius: 4px;
  padding: 10px 15px;
  margin-top: 15px;
  border-left: 3px solid #409EFF;
}

.charge-notice p {
  margin: 5px 0;
  font-size: 13px;
  color: #606266;
}

.history-filter {
  margin-bottom: 20px;
  display: flex;
  gap: 15px;
  color: #606266;
}

.empty-data-container {
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 200px;
  width: 100%;
  height: 200px;
  margin: 20px 0;
}

.empty-data {
  text-align: center;
}

.empty-data img {
  width: 80px;
  height: 80px;
  opacity: 0.6;
}

.empty-data p {
  color: #909399;
  margin-top: 8px;
}

.empty-hint {
  font-size: 12px;
  color: #c0c4cc;
}

/* 会员中心标签页样式 */
.membership-section {
  text-align: center;
  padding: 10px 0;
}

.membership-plans {
  display: flex;
  justify-content: center;
  gap: 18px;
  flex-wrap: wrap;
  margin-top: 20px;
  padding: 0 20px;
}

/* 添加权限说明区域样式 */
.permission-explanation {
  margin-top: 40px;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e1e6ef;
}

.permission-notes {
  margin-top: 20px;
  text-align: left;
  padding: 15px;
  background-color: #f2f6fc;
  border-radius: 4px;
  color: #606266;
}

.note-title {
  font-weight: bold;
  margin-bottom: 10px;
  color: #409EFF;
}

.permission-notes p {
  margin-bottom: 8px;
  line-height: 1.6;
}

.plan-card {
  width: 190px;
  min-height: 440px;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  padding: 20px 12px 25px;
  text-align: center;
  transition: all 0.3s ease;
  background-color: #fff;
  position: relative;
  overflow: visible;
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
  margin-bottom: 20px;
}

.plan-card:hover {
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
  transform: translateY(-5px);
}

.plan-tag {
  display: inline-block;
  padding: 4px 12px;
  border-radius: 16px;
  font-size: 14px;
  margin-bottom: 10px;
  background-color: #f5f5f5;
  color: #333;
  position: relative;
  z-index: 1;
}

/* 动态标签样式由 getPlanTagStyle() 方法生成 */

.plan-desc {
  color: #606266;
  margin-bottom: 15px;
  font-size: 13px;
}

.plan-price {
  font-size: 26px;
  font-weight: bold;
  color: #333;
  margin-bottom: 15px;
  position: relative;
  display: inline-block;
}

.plan-price::after {
  content: '';
  position: absolute;
  bottom: -6px;
  left: 50%;
  transform: translateX(-50%);
  width: 30px;
  height: 2px;
  background-color: #409EFF;
  border-radius: 2px;
}

.plan-price span {
  font-size: 13px;
  font-weight: normal;
}

.plan-btn {
  width: 90%;
  margin: 10px auto 20px;
  transition: all 0.3s ease;
  font-size: 13px;
  padding: 8px 15px;
  height: auto;
}

.upgrade-btn {
  color: white;
  border: none;
}

.plan-features {
  text-align: left;
  margin-top: 10px;
  flex-grow: 1;
  width: 100%;
  padding: 0 5px;
}

.feature-title {
  color: #333;
  margin-bottom: 12px;
  font-weight: 500;
  position: relative;
  padding-bottom: 5px;
  font-size: 13px;
}

.feature-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
  height: 180px;
}

.feature-item {
  display: flex;
  align-items: center;
  gap: 5px;
  font-size: 13px;
  color: #333;
  line-height: 1.3;
  flex-wrap: nowrap;
  width: 100%;
  box-sizing: border-box;
}

.feature-item .el-icon {
  margin-top: 0;
  flex-shrink: 0;
}

.feature-item span {
  flex: 1;
}

.feature-item.disabled {
  color: #909399;
}

.feature-tag {
  color: #409EFF;
  font-size: 9px;
  margin-left: 2px;
  background-color: #ecf5ff;
  padding: 0 2px;
  border-radius: 3px;
  display: inline-block;
  line-height: 1.3;
  white-space: nowrap;
}

.current-vip-info {
  background: linear-gradient(135deg, #f8f9fa, #ecf5ff);
  border-radius: 8px;
  padding: 12px 15px;
  margin: 15px auto 20px;
  max-width: 450px;
  border: 1px solid #e1e6ef;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-wrap: wrap;
  gap: 15px;
}

.vip-badge {
  padding: 5px 15px;
  border-radius: 20px;
  font-size: 14px;
  font-weight: bold;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

.vip-expire {
  font-size: 14px;
  color: #606266;
}

.expire-countdown {
  color: #E6A23C;
  font-weight: bold;
}

/* 低于30天显示警示色 */
.expire-countdown.warning {
  color: #F56C6C;
}

@media (max-width: 768px) {
  .membership-plans {
    flex-direction: column;
    align-items: center;
    gap: 25px;
  }

  .plan-card {
    width: 90%;
    max-width: 220px;
  }

  .current-plan {
    transform: none;
    order: -1;
  }
}

/* 资料设置标签页样式 */
.user-info-container {
  padding: 20px;
  background-color: #ffffff;
  border-radius: 4px;
  border: 1px solid #ebeef5;
}

.user-form {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.login-prompt {
  text-align: center;
  padding: 40px;
  background-color: #fff;
  border-radius: 4px;
  margin-bottom: 20px;
}

.prompt-icon {
  width: 64px;
  height: 64px;
  margin-bottom: 15px;
}

.prompt-title {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin-bottom: 5px;
}

.prompt-desc {
  color: #909399;
  font-size: 14px;
}

.empty-icon {
  width: 64px;
  height: 64px;
  margin-bottom: 15px;
}

.fancy-title {
  position: relative;
  font-size: 22px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 30px;
  text-align: center;
  padding-bottom: 15px;
}

.fancy-title::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 80px;
  height: 3px;
  background: linear-gradient(90deg, #409EFF, #007BFF);
  border-radius: 3px;
}

.centered-form {
  max-width: 600px;
  margin: 0 auto;
  position: relative;
}

.password-form-container, .user-info-container {
  padding: 30px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 6px 16px -8px rgba(0, 0, 0, 0.08),
  0 9px 28px 0 rgba(0, 0, 0, 0.05),
  0 12px 48px 16px rgba(0, 0, 0, 0.03);
  transition: all 0.3s ease;
}

.password-form-container:hover, .user-info-container:hover {
  box-shadow: 0 8px 24px -4px rgba(0, 0, 0, 0.12),
  0 12px 36px 0 rgba(0, 0, 0, 0.08),
  0 16px 60px 20px rgba(0, 0, 0, 0.05);
  transform: translateY(-2px);
}

.password-form, .user-form {
  width: 100%;
}

.form-actions {
  display: flex;
  justify-content: center;
  margin-top: 30px;
}

.submit-btn, .action-btn {
  background: linear-gradient(135deg, #409EFF, #007BFF);
  border: none;
  padding: 10px 20px;
  transition: all 0.3s ease;
}

.submit-btn:hover, .action-btn:hover {
  background: linear-gradient(135deg, #007BFF, #409EFF);
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}

.reset-btn {
  border: 1px solid #DCDFE6;
  padding: 10px 20px;
  transition: all 0.3s ease;
}

.reset-btn:hover {
  border-color: #C6E2FF;
  color: #409EFF;
  background-color: #F2F8FF;
}

.form-input-group {
  display: flex;
  align-items: center;
  width: 100%;
}

.form-input-group .el-input {
  flex: 1;
}

.form-input-group .action-btn {
  margin-left: 15px;
  border-radius: 4px;
}

.form-item-with-button {
  margin-bottom: 22px;
}

.read-only-item {
  margin-bottom: 22px;
}

.read-only-item .el-input {
  width: 65%;
}

.info-display-group {
  display: flex;
  align-items: center;
}

.member-badge {
  padding: 4px 12px;
  border-radius: 20px;
  font-size: 12px;
  margin-left: 15px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

.level-0 {
  background: linear-gradient(135deg, #E1F3D8, #C2E0B2);
  color: #397324;
}

.level-1 {
  background: linear-gradient(135deg, #FFF2E8, #FFD8B8);
  color: #D46B08;
}

.level-2 {
  background: linear-gradient(135deg, #FFF7E6, #FFE7BA);
  color: #D48A08;
}

.level-3 {
  background: linear-gradient(135deg, #E6F7FF, #BAE7FF);
  color: #096DD9;
}

/* 添加用户信息概览的样式 */
.user-stats-overview {
  background: linear-gradient(135deg, #f8f9fa, #ecf5ff);
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 25px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  border: 1px solid #e1e6ef;
  position: relative;
}

.user-stats-overview::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 5px;
  height: 100%;
  background: linear-gradient(to bottom, #409EFF, #007BFF);
  border-top-left-radius: 8px;
  border-bottom-left-radius: 8px;
}

.stats-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  border-bottom: 1px solid #e1e6ef;
  padding-bottom: 10px;
}

.stats-header h3 {
  margin: 0;
  font-size: 16px;
  color: #303133;
}

.form-group-row {
  display: flex;
  margin-bottom: 15px;
  align-items: center;
  padding: 5px 0;
}

.form-group-row:last-child {
  margin-bottom: 0;
}

.form-label {
  width: 170px;
  color: #606266;
  text-align: right;
  padding-right: 15px;
  font-weight: 500;
}

.form-value {
  flex: 1;
  color: #303133;
  font-weight: 500;
}

.form-value .member-badge {
  display: inline-block;
}

/* 专属客服标签页样式 */
.customer-service-section {
  text-align: center;
}

.service-container {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 30px;
}

.qrcode-container {
  text-align: center;
}

.customer-qrcode {
  width: 220px;
  height: 220px;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  padding: 15px;
  background-color: #fff;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  margin: 0 auto;
}

.customer-qrcode:hover {
  transform: scale(1.02);
  box-shadow: 0 6px 15px rgba(0, 0, 0, 0.15);
}

.qrcode-hint {
  color: #606266;
  margin-top: 15px;
  font-size: 15px;
}

.mt-30 {
  margin-top: 30px;
}

.service-desc {
  text-align: left;
}

.service-desc h3 {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin-bottom: 10px;
}

.service-desc p {
  color: #606266;
  font-size: 14px;
  margin-bottom: 8px;
}

.service-note {
  margin-top: 15px;
  color: #E6A23C;
  font-size: 13px;
  background-color: #FDF6EC;
  padding: 8px 12px;
  border-radius: 4px;
  border-left: 3px solid #E6A23C;
}

.current-plan {
  border: 2px solid #409EFF !important;
  box-shadow: 0 8px 24px rgba(64, 158, 255, 0.2) !important;
}

.current-plan::after {
  content: none;
  display: none;
}

/* 动态按钮样式由 getPlanButtonStyle() 方法生成 */

.plan-btn.upgrade-btn:hover {
  opacity: 0.9;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

/* 功能服务标签页样式 */
.function-service-section {
  text-align: center;
}

.function-container {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 30px;
  min-height: 300px;
}

/* 功能服务页面样式 */
.package-cards {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  margin-top: 20px;
}

.package-card {
  width: 280px;
  padding: 20px;
  border-radius: 8px;
  padding: 15px;
  text-align: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.country-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.country-code {
  font-size: 18px;
  font-weight: bold;
  color: #409EFF;
  margin-bottom: 5px;
}

.country-name {
  font-size: 14px;
  color: #606266;
  margin-bottom: 8px;
}

.country-price {
  font-size: 16px;
  color: #f56c6c;
  font-weight: 500;
}

.toggle-view-btn {
  margin: 20px 0;
  text-align: center;
}

.search-bar {
  max-width: 400px;
  margin: 0 auto 20px;
}

.search-input {
  width: 100%;
}

.show-all-countries {
  display: none;
}

.show-all-countries .country-card {
  width: calc(20% - 10px);
}

.raw-value {
  font-size: 12px;
  color: #999;
  margin-left: 8px;
}

.table-header-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.record-count {
  font-size: 14px;
  color: #606266;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-top: 15px;
}

/* 资料设置页样式 */
.profile-settings-container {
  display: flex;
  gap: 20px;
  margin-top: 10px;
}

.profile-settings-nav {
  width: 200px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  padding: 15px 0;
}

.nav-item {
  display: flex;
  align-items: center;
  padding: 15px 20px;
  cursor: pointer;
  transition: all 0.3s;
  border-left: 3px solid transparent;
}

.nav-item:hover {
  background-color: #f5f7fa;
}

.nav-item.active {
  background-color: #ecf5ff;
  border-left: 3px solid #409eff;
  color: #409eff;
}

.nav-item i {
  margin-right: 10px;
  font-size: 18px;
}

.profile-settings-content {
  flex: 1;
}

.settings-panel {
  background-color: #fff;
  border-radius: 8px;
  padding: 0;
}

.panel-header {
  margin-bottom: 20px;
}

.panel-header h3 {
  font-size: 18px;
  margin: 0 0 8px 0;
  color: #303133;
}

.panel-desc {
  color: #909399;
  font-size: 14px;
  margin: 0;
}

.profile-card, .security-card {
  margin-bottom: 20px;
}

.profile-info {
  display: flex;
  gap: 30px;
}

.avatar-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 15px;
}

.info-form {
  flex: 1;
}

.upload-btn {
  width: 100px;
}

.security-section {
  margin-bottom: 20px;
}

.section-header {
  margin-bottom: 20px;
}

.section-header h4 {
  font-size: 16px;
  margin: 0 0 8px 0;
  color: #303133;
}

.section-desc {
  color: #909399;
  font-size: 14px;
  margin: 0;
}

.security-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 0;
}

.security-info {
  display: flex;
  align-items: center;
  gap: 15px;
}

.security-icon {
  font-size: 24px;
  color: #409eff;
}

.security-title {
  font-size: 15px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 5px;
}

.security-value {
  font-size: 14px;
  color: #606266;
}

/* 推广系统标签页样式 */
.promotion-section {
  text-align: left;
}

.promotion-container {
  margin-top: 20px;
}

.promotion-description {
  background-color: #f8f9fa;
  padding: 15px;
  border-radius: 8px;
  margin-bottom: 20px;
  border-left: 3px solid #409EFF;
}

.promotion-description p {
  margin: 0;
  font-size: 15px;
  color: #606266;
  line-height: 1.6;
}

.promotion-link-box {
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.link-header {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 15px;
}

.promotion-input {
  width: 100%;
}

.promotion-qrcode-box {
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.qrcode-title {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 15px;
}

.qrcode-wrapper {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.qrcode-image {
  margin-bottom: 15px;
  padding: 10px;
  background-color: #fff;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.promotion-stats {
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.stats-title {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 15px;
}

.stats-cards {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
}

.stat-card {
  flex: 1;
  min-width: 180px;
  background: linear-gradient(135deg, #ecf5ff, #d7e9fc);
  border-radius: 8px;
  padding: 15px;
  text-align: center;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #409EFF;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: #606266;
}

.commission-records {
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.records-title {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 15px;
}

.empty-service {
  text-align: center;
  color: #909399;
  margin-top: 20px;
}

/* 在style部分添加以下样式 */
.plan-duration {
  font-size: 14px;
  color: #606266;
  margin-top: -5px;
  margin-bottom: 10px;
}

.membership-plans .plan-card {
  /* 保持现有样式 */
  position: relative;
  width: 240px;
  background-color: #fff;
  border-radius: 8px;
  padding: 24px 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  transition: all 0.3s;
  margin: 0 15px 15px 0;
}

/* 支付相关样式 */
.payment-form {
  width: 100%;
  min-height: 200px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.qrcode-container {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px 0;
}

.qrcode-image {
  max-width: 200px;
  max-height: 200px;
}

/* 添加套餐有效期样式 */
.package-duration {
  font-size: 14px;
  color: #606266;
  margin-bottom: 15px;
  background-color: #f5f7fa;
  padding: 5px 10px;
  border-radius: 4px;
  display: inline-block;
}

/* 套餐说明样式 */
.package-description, .vip-description {
  background-color: #f8f9fa;
  border-radius: 8px;
  padding: 15px 20px;
  margin-bottom: 20px;
  border-left: 3px solid #409EFF;
}

.description-title {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 10px;
}

.description-list {
  margin: 0;
  padding-left: 20px;
}

.description-list li {
  margin-bottom: 8px;
  display: flex;
  align-items: flex-start;
  gap: 8px;
  line-height: 1.5;
}

.description-list li .el-icon {
  margin-top: 3px;
  flex-shrink: 0;
}

.highlight-text {
  color: #409EFF;
  font-weight: bold;
  margin: 0 2px;
}

.section-header {
  margin-bottom: 20px;
}

.section-title-wrapper {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 10px;
}

.section-title-text {
  margin: 0;
  font-size: 16px;
  color: #303133;
}

.empty-package {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 200px;
  padding: 30px 0;
}

/* 当前方案标识 */
.current-plan-badge {
  position: absolute;
  top: -10px;
  right: -10px;
  background: linear-gradient(135deg, #409EFF, #007BFF);
  color: white;
  padding: 5px 10px;
  border-radius: 15px;
  font-size: 12px;
  font-weight: bold;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
  z-index: 1;
}
</style> 